<template>
  <view :class="{ 'view-link-button': fileId }" @click.stop="onViewLink">
    {{ fileId ? title : '-' }}
  </view>
</template>
<script setup>
  import { getFileSingle } from '@/api/common/index'
  const props = defineProps({
    fileId: [String, Number],
    title: {
      type: String,
      default: '查看附件',
    },
  })
  // 查看附件
  const onViewLink = () => {
    if (props.fileId) {
      getFileSingle({ id: props.fileId }).then((res) => {
        const result = res.result
        if (result) {
          const fileName = result.originalFileName
          const fileUrl = result.openUrl
          const fileExt = fileName.split('.').pop().toLowerCase()
          // 图片预览
          if (['jpg', 'jpeg', 'png'].includes(fileExt)) {
            uni.previewImage({
              urls: [fileUrl],
            })
          } else {
            // #ifdef APP-PLUS
            uni.downloadFile({
              url: fileUrl,
              success: function (res) {
                // 下载成功
                uni.openDocument({ filePath: res.tempFilePath })
              },
              fail: function () {
                // 下载失败
                uni.showToast({
                  title: '下载失败',
                  icon: 'none',
                })
              },
            })
            // #endif
            // #ifdef H5
            window.open(fileUrl)
            // #endif
          }
        }
      })
    }
  }
</script>
<style lang="scss" scoped>
  .view-link-button {
    color: #3072f6;
    text-decoration: underline;
    text-underline-offset: 10rpx;
  }
</style>
